// serwer.go
package types

import (
	"strings"
	//	"log"
	"net/http"
)

type PathMux map[string]func(http.ResponseWriter, *http.Request)

type Mux struct {
	MethodMux map[string]PathMux
}

func NewMux() *Mux {
	mux := &Mux{}
	mux.MethodMux = map[string]PathMux{
		"GET":    PathMux{},
		"POST":   PathMux{},
		"PUT":    PathMux{},
		"DELETE": PathMux{},
		"HEAD":   PathMux{},
		"PATCH":  PathMux{},
	}
	return mux
}

/*
func (handler *Handler) MuxRegister(method string, url string, handleFunc func(http.ResponseWriter, *http.Request)) {
	hmux := handler.mux[method]
	hmux[url] = handleFunc
}
*/
func (mux Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if pathMux, ok := mux.MethodMux[strings.ToUpper(r.Method)]; !ok {
		w.Write([]byte("Error Method Request!"))
	} else {
		if handleFunc, ok := pathMux[r.URL.Path]; !ok {
			w.Write([]byte("Error Request!"))
		} else {
			handleFunc(w, r)
		}
	}
}

func (mux *Mux) Get(path string, handleFunc func(http.ResponseWriter, *http.Request)) {
	pathMux := mux.MethodMux["GET"]
	pathMux[path] = handleFunc
}

func (mux *Mux) Post(path string, handleFunc func(http.ResponseWriter, *http.Request)) {
	pathMux := mux.MethodMux["POST"]
	pathMux[path] = handleFunc
}

func (mux *Mux) Put(path string, handleFunc func(http.ResponseWriter, *http.Request)) {
	pathMux := mux.MethodMux["PUT"]
	pathMux[path] = handleFunc
}

func (mux *Mux) Delete(path string, handleFunc func(http.ResponseWriter, *http.Request)) {
	pathMux := mux.MethodMux["DELETE"]
	pathMux[path] = handleFunc
}

func (mux *Mux) Head(path string, handleFunc func(http.ResponseWriter, *http.Request)) {
	pathMux := mux.MethodMux["HEAD"]
	pathMux[path] = handleFunc
}

func (mux *Mux) Patch(path string, handleFunc func(http.ResponseWriter, *http.Request)) {
	pathMux := mux.MethodMux["PATCH"]
	pathMux[path] = handleFunc
}
